<template>
  <div class="app-page">
    <aside-tree
      title="自动催单设置"
      :tree-data="treeData"
      :mouse-button="false"
      :loading="$loadingPlugin.getTreeData"
      @currentChange="currentChange"
      @refresh="getTreeData"
    />
    <div class="table">
      <div style="margin-bottom: 10px;" class="btn-group">
        <div>
          <el-button v-permission="1" type="primary" icon="el-icon-search" @click="search">查询</el-button>
          <el-button v-permission="1" type="primary" icon="el-icon-plus" @click="add">新增</el-button>
        </div>
      </div>
      <div style="margin-bottom: 10px;" class="btn-group">
        <div>
          <el-checkbox v-model="checked" @change="change">包含下级</el-checkbox>
        </div>
      </div>
      <lb-table
        ref="lbTable"
        v-loading="$loadingPlugin.fetchData"
        v-el-height-adaptive-table="{bottomOffset:10}"
        border
        highlight-current-row
        element-loading-text="加载中"
        :column="column"
        :data="tableData.data"
        pagination
        :total="tableData.total"
        custom-column
        :immediate-fetch="false"
        default-open
        @fetch="fetchData"
      />
    </div>
    <add ref="add" @upDataSet="upDataSet" />
    <edit ref="edit" />
  </div>
</template>

<script>
  import getTreeData from '@/utils/jsonTree'
  import AsideTree from '@/views/components/OrgTree'
  import { organizationQueryList, voluntarilyReminderList, voluntarilyReminderChangeStatus, voluntarilyReminderChangeDelete } from '@/api'
  import Add from './components/Add.vue'
  import Edit from './components/Edit.vue'

  export default {
    name: 'autoReminderSetting',
    components: {
      AsideTree,
      Add,
      Edit
    },
    data() {
      return {
        actionColWidth: 80,
        treeData: [],
        checked: false,
        current: {},
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      column: function() {
        return [
          { type: 'index' },
          {
            prop: 'orgName',
            label: '机构'
          },
          {
            prop: 'month',
            label: '月份',
            render: (h, { row, $index }) => <span>{(row.startMonth + '月') + '~' + (row.endMonth + '月')}</span>
          },
          {
            prop: 'periodDesc',
            label: '催单时段'
          },
          {
            prop: 'intervalDesc',
            label: '催单间隔(分钟)'
          },
          {
            prop: 'isOpen',
            label: '是否开启',
            render: (h, { row, $index }) => <span>{row.isOpen === 1 ? '开启' : '关闭'}</span>
          },
          {
            label: '操作',
            className: 'action-col',
            width: this.actionColWidth,
            align: 'center',
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
                <div>
                  <el-link v-permission='3' underline={false} size='mini' onClick={() => this.openFlow(row)}>编辑</el-link>
                  <el-link v-permission='4' underline={false} size='mini' onClick={() => this.delete(row)}>删除</el-link>
                  <el-link v-permission='5' underline={false} size='mini' onClick={() => this.open(row)}>开启/关闭</el-link>
                </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      await this.getTreeData() // 机构
    },
    methods: {
      async fetchData({ currentPage, pageSize }) {
        const params = {}
        if (this.checked) {
          params['orgId'] = 0
          params['orgSNNo'] = this.current.orgSNNo
        } else {
          params['orgId'] = this.current.orgId
        }
        const res = await voluntarilyReminderList({
          ...params,
          currentPage,
          pageSize
        })
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 是否包含下级
      async change() {
        await this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 查询
      async search() {
        await this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 新增
      async add() {
        await this.$refs.add.open(this.current)
        // this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 编辑
      async openFlow(row) {
        await this.$refs.edit.open(row)
      },
      // 开启/关闭
      open(row) {
        var isOpen = row.isOpen
        var msg = ''
        if (isOpen === 1) {
          msg = '确认要禁用吗?'
          isOpen = -1
        } else {
          msg = '确认要启用吗?'
          isOpen = 1
        }
        this.$confirm(`${msg}`, '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const res = await voluntarilyReminderChangeStatus({
            id: row.id,
            isOpen: isOpen
          })
          if (res.status === 200) {
            this.$refs.lbTable.fetch({ currentPage: 1 })
          }
        })
      },
      // 删除
      delete(row) {
        this.$confirm('确认要删除吗？', '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const res = await voluntarilyReminderChangeDelete({ id: row.id })
          if (res.status === 200) {
            this.$refs.lbTable.fetch({ currentPage: 1 })
          }
        })
      },
      // 更新数据
      upDataSet() {
        console.log('更新数据')
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 清除对象空属性
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      // 选择组织机构变化
      currentChange(current) {
        if (current) {
          this.current = current
          this.$refs.lbTable.fetch({ currentPage: 1 })
        } else {
          this.$message({
            message: '请选择机构',
            type: 'warning'
          })
        }
      },
      // 获取组织机构数据
      async getTreeData() {
        const res = await organizationQueryList()
        const data = res.data.map(item => ({
          label: item.orgName,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.app-page {
  display: flex;
  height: calc(100vh - 125px);
  padding: 0;
  .table {
    width: calc(100% - 270px);
    margin-left: 10px;
  }
}
</style>
